'use strict'

const xml2js = require('xml2js');
const Promise = require('bluebird');
const tpl = require('./tpl');

exports.parseXMLAsync = xml => {

    return new Promise((resolve, reject) => {
            xml2js.parseString(xml, { trim: true }, (err, content) => {
            if(err) reject(err);
            else resolve(content);
        });
    });
};

exports.formatMessage = result => {
    let message = {};
    result = JSON.parse(JSON.stringify(result));

    for(let key in result) {
        // 只接受数组

        if(result[key].length === 1) {

            if(typeof result[key][0] === 'object') {
                message[key] = formatMessage(result[key]);
            } else {
                message[key] = (result[key][0] || '').trim();
            }
        } else {

            // 遍历数组
            message[key] = [];

            for(let val of result[key]) {
                message[key].push(formatMessage(val));
            }
        }
    }

    return message;
};

exports.tpl = (content, message) => {

    let info = {};
    let type = 'text';
    let fromUserName = message.FromUserName;
    let toUserName = message.ToUserName;

    if(Array.isArray(content)) {
        type = 'news';
    }

    type = content.type || type;
    info.content = content;
    info.createTime = new Date().getTime();
    info.msgType = type;
    info.fromUserName = toUserName;
    info.toUserName = fromUserName;

    return tpl.compiled(info);
};
